package com.review.dp;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

public class LC_45 {
    // 动态规划
    public static int jump(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        dp[0] = 0;

        for (int i = 1; i < n; i++) {
            dp[i] = n;
            for (int j = 0; j < i; j++) {
                if (nums[j] + j >= i) {
                    dp[i] = Math.min(dp[i], dp[j] + 1);
                }
            }
        }
        return dp[n - 1];
    }

    // BFS
    public static int jump_2(int[] nums) {
        if (nums.length <= 1) return 0;
        int count = 0;
        Queue<Integer> queue = new LinkedList<>();
        Set<Integer> visited = new HashSet<>();
        queue.add(0);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int poll = queue.poll();
                while (nums[poll] != 0) {
                    if (visited.contains(poll + nums[poll])) {
                        nums[poll]--;
                        continue;
                    }
                    if (poll + nums[poll] == nums.length - 1) return count + 1;
                    visited.add(poll + nums[poll]);
                    queue.add(poll + nums[poll]);
                    nums[poll]--;
                }
            }
            count++;
        }

        return count;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 1, 4};
        System.out.println(jump(nums));
        System.out.println(jump_2(nums));
    }
}
